package com.zbkj.crmeb.task.product;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.ProductUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.store.dao.StoreProductMerDao;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.service.StoreProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Configuration
public class ProductOperateTask {

    @Resource
    private IChannelMerchantService channelMerchantService;
    @Resource
    private StoreProductService storeProductService;
    @Resource
    private StoreProductMerDao storeProductMerDao;
    @Resource
    private ProductUtil productUtil;

    @XxlJob("showProductByMerId")
    public void showProductByMerId(){
        String[] split = XxlJobHelper.getJobParam().split(",");
        if (split.length<2){
            return;
        }
        String merId = split[0];
        String isShow = Objects.equals(split[1],"Y")?"0":"1";

        if (StringUtils.isBlank(merId)){
            return;
        }
        long start = System.currentTimeMillis();
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (null == channelMerchant || StringUtils.isBlank(channelMerchant.getSuppliersIds())){
            return;
        }
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        if (CollectionUtils.isEmpty(suppliersIdList)){
            return;
        }
        // 供应商上架数据
        int count = storeProductService.count(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getSuppliersId, suppliersIdList).eq(StoreProduct::getIsShow,true));
        if (count<=0){
            return;
        }
        // mock个请求，懒得改jar包
        MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
        mockHttpServletRequest.addHeader("mer_id",merId);
        ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockHttpServletRequest);
        RequestContextHolder.setRequestAttributes(servletRequestAttributes);

        int maxPage = (count+999)/1000;
        int pageNo = 1;
        try {
            while (pageNo<=maxPage){
                try {
                    Page<StoreProduct> page = PageHelper.startPage(pageNo, 1000);
                    storeProductService.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getSuppliersId, suppliersIdList).eq(StoreProduct::getIsShow,true));
                    List<StoreProduct> storeProducts = page.getResult();
                    if (CollectionUtils.isEmpty(storeProducts)){
                        continue;
                    }
                    List<Integer> productIds = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
                    List<StoreProductMer> storeProductMers = storeProductMerDao.selectList(Wrappers.<StoreProductMer>lambdaQuery().in(StoreProductMer::getProductId, productIds));
                    if (CollectionUtils.isEmpty(storeProductMers)){
                        continue;
                    }
                    Map<Integer, StoreProductMer> productMerMap = storeProductMers.stream().collect(Collectors.toMap(StoreProductMer::getProductId, v -> v));
                    for (StoreProduct storeProduct : storeProducts) {
                        if (!productUtil.checkShippingTemp(storeProduct)) {
                            log.warn("{},{},请先填写对应运费模板信息",storeProduct.getId(),storeProduct.getStoreName());
                            continue;
                        }
                        Integer productId = storeProduct.getId();
                        StoreProductMer storeMerProduct = productMerMap.get(productId);
                        if (null == storeMerProduct){
                            storeMerProduct = new StoreProductMer();
                            storeMerProduct.setProductId(productId);
                            storeMerProduct.setIsNotShow(isShow);
                            storeMerProduct.setIsSystemOut(0);
                            storeMerProduct.setCreateTime(new Date());
                            storeMerProduct.setUpdateTime(new Date());
                            storeProductMerDao.insert(storeMerProduct);
                            continue;
                        }
                        storeMerProduct.setIsNotShow(isShow);
                        storeMerProduct.setIsSystemOut(0);
                        storeMerProduct.setUpdateTime(new Date());
                        storeProductMerDao.updateById(storeMerProduct);
                    }
                }catch (Exception e){
                    log.error("{}，全量上架供应商商品异常：",channelMerchant.getChannelName(),e);
                }finally {
                    pageNo++;
                }
            }
        }catch (Exception e){
            log.error("全量上架供应商商品失败",e);
        }finally {
            RequestContextHolder.resetRequestAttributes();
            log.info("全量上架供应商商品完成，耗时: {}",(System.currentTimeMillis()-start)/1000/60);
        }
    }
}
